<template>
    <div class="playMusic" v-show="isShow">
        <div class="bg" :style="{backgroundImage:`url(${playlist[playCurrentIndex].al.picUrl})`}"></div>
        <div class="playTop">
            <svg class="icon" aria-hidden="true" @click="setIsShow(false)">
                <use xlink:href="#icon-zuo1"></use>
            </svg>
            <div class="center">
                <div class="title">
                    <marquee behavior="scroll" direction="left">{{playlist[playCurrentIndex].name}}</marquee>
                </div>
            </div>
            <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-fenxiang-"></use>
            </svg>
        </div>
        <audio id="audio" ref='audio' :src="`https://music.163.com/song/media/outer/url?id=${playlist[playCurrentIndex].id}.mp3`" />
        <div class="Progress">
            <div class="time">{{this.timeToString(currentTime)}} : {{totalTime}}</div>
            <div class="Progress_1" ref="wid" @click="getMouseXY($event)"></div>
            <div :style="{width: `${num}rem`}" class="Progress_2" @click="getMouseXY($event)"></div>
            <div :style="{marginLeft: `${num}rem`}" class="Progress_round"></div>
        </div>
         <div class="playFooter">
            <svg class="icon" aria-hidden="true" v-if="playType==1" @click="qieHuang">
                <use xlink:href="#icon-liebiaoxunhuan"></use>
            </svg>
            <svg class="icon" aria-hidden="true" v-else-if="playType==2" @click="qieHuang">
                <use xlink:href="#icon-suijibofang"></use>
            </svg>
            <svg class="icon" aria-hidden="true" v-else @click="qieHuang">
                <use xlink:href="#icon-danxunhuan"></use>
            </svg>
            <svg class="icon" aria-hidden="true" @click="goPlay(-1)">
                <use xlink:href="#icon-shangyishoushangyige"></use>
            </svg>
            <svg v-if="!playing"  class="icon play" aria-hidden="true" @click="play">
                <use xlink:href="#icon-bofang3"></use>
            </svg>
            <svg v-else class="icon play" aria-hidden="true" @click="play">
                <use xlink:href="#icon-zanting"></use>
            </svg>
            <svg class="icon" aria-hidden="true" @click="goPlay(1)">
                <use xlink:href="#icon-xiayigexiayishou"></use>
            </svg>
            <svg class="icon" aria-hidden="true" @click="liebiao()">
                <use xlink:href="#icon-liebiao2"></use>
            </svg>
        </div>
        <div class="lyricList" ref="ric">
          <p v-for="(item,i) in lyric" :key="i" :class="{'active':is===i}" >{{item.text}}</p>
        </div>
    </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
import { getlyric } from '@/api/index.js'
export default {
  props: ['liebiao'],
  computed: {
    ...mapState(['playlist', 'playCurrentIndex', 'isShow', 'playing'])
  },
  data () {
    return {
      // 播放状态
      currentTime: 0, // 当前播放时间
      totalTime: '00:00', // 总播放时间
      progressScaleX: 0, // 播放进度
      error: '', // 报错内容
      playType: 1, // 播放类型：1-列表循环，2-随机播放，3-单曲循环
      listShow: false, // 播放列表是否展示
      num: 0,
      lyric: [],
      is: 0

    }
  },
  methods: {
    ...mapMutations(['setIsShow']),
    init () {
      this.Progress()
      this.gitLyric()
      const time = this.playlist[this.playCurrentIndex].dt
      // 总播放时间
      this.totalTime = this.timeToString(time / 1000)
    },
    play () {
      if (this.playing) { // 播放中,点击则为暂停
        this.$store.commit('setPlaying', false)
        this.$refs.audio.pause()
      } else { // 暂停中,点击则为播放
        this.$store.commit('setPlaying', true)
        this.$refs.audio.play()
      }
    },
    goPlay (num) { // 上 下 首歌曲
      if (this.playing) {
        this.playing = false
        this.$refs.audio.pause()
      }
      var index = this.playCurrentIndex + num
      if (index < 0) {
        index = this.playlist.length - 1
      } else if (index === this.playlist.length) {
        index = 0
      }
      this.$store.commit('setPlayIndex', index)
      this.playing = true
      setTimeout(() => {
        this.currentTime = '00:00'
        this.$refs.audio.play()
      }, 100)
    },
    audioInit () {
      this.$refs.audio.addEventListener('ended', () => {
        if (this.playType === 1) {
          console.log('ended')
          var index = this.playCurrentIndex
          if (index + 1 === this.playlist.length) {
            index = 0
          } else {
            index = index + 1
          }
          this.$store.commit('setPlayIndex', index)
        } else if (this.playType === 2) {
          index = Math.round(Math.random() * this.playlist.length - 1)
          this.$store.commit('setPlayIndex', index)
        }
        // 此处需要一定的延迟让audio的dom结构获取到
        setTimeout(() => {
          this.$refs.audio.play()
        }, 100)
      }, true)
    },
    qieHuang () {
      if (this.playType + 1 > 3) {
        this.playType = 1
      } else {
        this.playType = this.playType + 1
      }
    },
    Progress () {
      // const divWid = this.$refs.wid.clientWidth
      this.$refs.audio.addEventListener('timeupdate', () => {
        // 当前播放时间
        this.currentTime = this.$refs.audio.currentTime
        // 当前播放进度百分比
        this.progressScaleX = this.$refs.audio.currentTime / this.$refs.audio.duration
        this.progressScaleX = parseFloat(this.progressScaleX).toFixed(2)
        this.num = this.progressScaleX * 6
      })
    },
    getMouseXY (e) {
      const screenWidth = document.body.clientWidth
      const x = e.x
      const gitE = x - (screenWidth - 6 * 50) / 2
      this.progressScaleX = parseFloat(gitE / (6 * 50)).toFixed(2)
      this.num = parseFloat(this.progressScaleX * 6).toFixed(2)
      this.$refs.audio.currentTime = this.$refs.audio.duration * this.progressScaleX
      this.Progress()
    },
    // 秒值转字符串
    timeToString (param) {
      param = parseInt(param)
      var mm = '00'; var ss = '00'
      if (param >= 0 && param < 60) {
        param < 10 ? ss = '0' + param : ss = param
        return '00:' + ss
      } else if (param >= 60 && param < 3600) {
        mm = parseInt(param / 60)
        if (mm < 10) {
          mm = '0' + mm
        }
        ss = param % 60
        if (ss < 10) {
          ss = '0' + ss
        }
        return mm + ':' + ss
      }
    },
    // 获取歌词
    async gitLyric () {
      this.lyric = []
      const gitlyric = await getlyric(this.playlist[this.playCurrentIndex].id)
      // console.log(gitlyric.data)
      this.formatLyric(gitlyric.data.lrc.lyric)
      //    console.log(this.lyric)
    },
    formatLyric (text) {
      const arr = text.split('\n') // 原歌词文本已经换好行了方便很多，我们直接通过换行符“\n”进行切割
      const row = arr.length // 获取歌词行数
      for (let i = 0; i < row; i++) {
        const temprow = arr[i] // 现在每一行格式大概就是这样"[00:04.302][02:10.00]hello world";
        const temparr = temprow.split(']')// 我们可以通过“]”对时间和文本进行分离
        const text = temparr.pop() // 把歌词文本从数组中剔除出来，获取到歌词文本了！
        // 再对剩下的歌词时间进行处理
        temparr.forEach(element => {
          const timearr = element.substr(1, element.length - 1).split(':')// 先把多余的“[”去掉，再分离出分、秒
          const s = parseInt(timearr[0]) * 60 + Math.ceil(timearr[1]) // 把时间转换成与currentTime相同的类型，方便待会实现滚动效果
          const obj = {
            text: text,
            s: s
          }
          this.lyric.push(obj) // 每一行歌词对象存到组件的lyric歌词属性里
        })
      }
      this.lyric.sort(this.sortRule)
    },
    sortRule (a, b) {
      return a.time - b.time
    }
  },
  mounted () {
    this.audioInit()
    this.Progress()
    this.gitLyric()
    const time = this.playlist[this.playCurrentIndex].dt
    // 总播放时间
    this.totalTime = this.timeToString(time / 1000)
  },
  watch: {
    currentTime () {
      const time = Math.ceil(this.currentTime)
      const p = document.querySelector('p.active')
      this.lyric.forEach((element, index) => {
        if (time === element.s && p != null) {
          this.is = index
          if (p.offsetTop >= 100) {
            this.$refs.ric.scrollTop = p.offsetTop - 100
          }
        }
      })
    },
    playCurrentIndex () {
      this.init()
      setTimeout(() => {
        this.$store.commit('setPlaying', true)
        this.$refs.audio.play()
      }, 100)
    }
  }
}
</script>
<style lang="less" scoped>
.playMusic{
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    background-color: #fff;
    z-index: 99;
    .bg{
        position:absolute;
        left: 0;
        top: 0;
        height: 100%;
        width: 100%;
        filter: blur(100px);
        background-size: cover;
    }
    .playTop{
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 7.5rem;
        height: 1.2rem;
        position: absolute;
        top: 0;
        left: 0;
        color:white;
        padding: 0 0.4rem;
        .icon{
            fill: white;
            width: 0.6rem;
            height: 0.6rem;
        }
        marquee{
            flex: 1;
            width: 5rem;
        }
    }
    .Progress{
        position:relative;
        top: 10.8rem;
        left: 0rem;
        .time{
            font-weight: 900;
            color: #000;
            font-size: 0.3rem;
            text-align: center;
            margin-bottom: 0.2rem;
        }
        .Progress_1{
            width: 6rem;
            height: 0.15rem;
            background-color:#000;
            margin: 0 auto;
            border-radius: 0.3rem;
        }
        .Progress_2{
            height: 0.15rem;
            background-color:red;
            border-radius: 0.3rem;
            position:absolute;
            top: 0.58rem;
            left: 0.76rem;
        }
        .Progress_round{
          width: 0.3rem;
          height: 0.3rem;
          background-color:red;
          position:absolute;
          top: 0.5rem;
          left: 0.47rem;
          border-radius: 50%;
          box-shadow: 0px 0px 10px white;
        }
    }
    .playContent{
        position:absolute;
        width: 7.5rem;
        height: 5rem;
        left: 0;
        top: 1.5rem;
        .needle{
            width: 2rem;
            height: auto;
            position:absolute;
            left: 45%;
            transform-origin: 0.3rem 0;
            transform: rotate(-20deg);
            transition: all 1s;
            z-index: 10;
        }
        .needle.active{
            transform: rotate(1deg);
            transition: all 1s;
            z-index: 10;
        }
        .disc{
            width: 5.5rem;
            height: auto;
            position:absolute;
            left: 13.33%;
            top: 1.8rem;
        }
        .playImg{
            width: 5.5rem;
            height: auto;
            position:absolute;
            left: 27%;
            top: 2.8rem;
            width: 46%;
            height: 70%;
            border-radius: 50%;
        }
    }
    .playFooter{
        width: 7.5rem;
        height: 1.5rem;
        position:absolute;
        left: 0;
        bottom: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 0.4rem;
        .icon{
            fill: white;
            width: 0.5rem;
            height: 0.5rem;
        }
        .play{
            width: 0.7rem;
            height: 0.7rem;
        }
    }
    .playLyric{
        position:absolute;
        width: 7.5rem;
        height: 6rem;
        left: 0;
        top: 1.5rem;
        overflow:scroll;
        padding: 0.2rem 0;
        text-align: center;
        .active{
            color: red;
        }
    }
    .lyricList{
      position: relative;
      top: 0.8rem;
      width: 100%;
      height: 60%;
      overflow:scroll;
      text-align: center;
      .active{
        color: red;
      }
    }
}
</style>
